const { collectionsModel } = require("../models/collectionsModels");

// 添加收藏题目
async function createCollections(req, res, next) {
  //传入参数{studentId,exerciseId}
  const { studentId, exerciseId } = req.body;
  const isHas = await collectionsModel.find({ studentId, exerciseId });
  if (isHas.length>0) {
    res.send({
      code: 500,
      message: '收藏数据已存在'
    })
  } else {
    const result = await collectionsModel.create({ studentId, exerciseId });
    if (result) {
      res.send({
        code: 200,
        message: "添加数据成功"
      });
    } else {
      res.send({
        code: 500,
        message: "添加数据失败"
      });
    }
  }

}
// 收藏获取所有数据接口
async function getCollections(req, res, next) {
  // 要传学生id {studentId}
  const result = await collectionsModel.find(req.body).populate("exerciseId");
  if (result.length > 0) {
    res.send({
      code: 200,
      message: "获取数据成功",
      result
    });
  } else {
    res.send({
      code: 500,
      message: "获取数据失败"
    });
  }
}
//删除收藏
async function deleteCollections(req, res, next) {
  const { _id } = req.body;
  const result = await collectionsModel.deleteOne({ _id });
  if (result.deletedCount != 0) {
    res.send({
      message: "删除成功",
      code: 200
    });
  } else {
    res.send({
      message: "删除失败",
      code: 500
    });
  }
}

module.exports = {
  getCollections,
  createCollections,
  deleteCollections
};
